package {

	import flash.display.*;
	import flash.events.Event;
	import flash.text.*;
	import flash.utils.natCaseCompare;
	import flash.utils.natCompare;

	[SWF (width = 800, height = 600)]
	public class AS3NatCompare extends Sprite {

		private var array:Array = ["", "1-02", "1-2", "1-20", "10-20", "Fred", "Jane", "PIC05", "Pic3", "Tom",
										 "X2-y7", "jane", "pic01", "pic02", "pic02a", "pic2", "pic4",
										 "pic 4 else", "pic 5", "pic 5 something", "pic  5", "pic 6",
										 "pic   7", "pic100", "pic100a", "pic120", "pic121", "pic02000", 
										 "x2-g8", "x2-y08", "x8-y8"];

		public function AS3NatCompare() {
			if (stage) {
				onAddedToStage();
			} else {
				addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			}

			// Run test
			junitTest();

			// Monospace font
			var format:TextFormat = new TextFormat("_typewriter", 12, 0xFFFFFF);

			var scrambled:Array = array.sort(shuffle);

			var scrambledTf:TextField = new TextField();
			scrambledTf.defaultTextFormat = format;
			scrambledTf.autoSize = TextFieldAutoSize.LEFT;
			scrambledTf.text = "Scrambled array:\n\n";
			scrambledTf.appendText(scrambled.toString().split(',').join('\n'));
			addChild(scrambledTf);

			var sorted:Array = scrambled.sort(natCompare);
			var sortedTf:TextField = new TextField();
			sortedTf.x = 150;
			sortedTf.defaultTextFormat = format;
			sortedTf.autoSize = TextFieldAutoSize.LEFT;
			sortedTf.text = "Case-sensitive sorted array:\n\n";
			sortedTf.appendText(sorted.toString().split(',').join('\n'));
			addChild(sortedTf);

			var caseSorted:Array = scrambled.sort(natCaseCompare);
			var caseSortedTf:TextField = new TextField();
			caseSortedTf.x = 400;
			caseSortedTf.defaultTextFormat = format;
			caseSortedTf.autoSize = TextFieldAutoSize.LEFT;
			caseSortedTf.text = "Case-insensitive sorted array:\n\n";
			caseSortedTf.appendText(caseSorted.toString().split(',').join('\n'));
			addChild(caseSortedTf);
		}

		private function shuffle(a:*, b:*):int {
			return (Math.random() - 0.5) * 100;
		}

		private function onAddedToStage(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
		}

		private function junitTest():void {
			var count:int = array.length;
			for (var i:int = 0; i < count; i++) {
				for (var j:int = 0; j < count; j++) {
					var s1:String = array[i];
					var s2:String = array[j];
					var res:int = natCaseCompare(s1, s2, false);
					if ((res == 1 && i <= j) || (res == -1 && i >= j) || (res == 0 && s1 != s2)) {
						// assert
						trace("wrong compare:", s1, (res > 0) ? ">" : (res < 0) ? "<" : "==", s2);
					}
				}
			}
		}

	}
}
